import React, {Component} from 'react';
import NfcManager, {NfcEvents} from 'react-native-nfc-manager';
import {View, Text, TouchableOpacity, PermissionsAndroid} from 'react-native'
import ToastUtil from "../../utils/ToastUtil";

class Msg extends Component {

    constructor() {
        super();
        this.state = {
            nfcInfo: '',
            flag: false
        }
    }

    componentDidMount() {
        this._navListener = this.props.navigation.addListener('didFocus', () => {
            this.initNfc()
            this.setState({
                nfcInfo: '',
                flag: true
            })

        });
        this._navListener2 = this.props.navigation.addListener('didBlur', () => {
            NfcManager.unregisterTagEvent().catch(() => 0);
        });
    }
    componentWillUnmount() {
        this._navListener && this._navListener.remove();
        this._navListener2 && this._navListener2.remove()
    }


    async initNfc() {
        await NfcManager.start();
    }

    readNdef() {
        const cleanUp = () => {
            NfcManager.setEventListener(NfcEvents.DiscoverTag, null);
            NfcManager.setEventListener(NfcEvents.SessionClosed, null);
        };

        return new Promise((resolve) => {
            let tagFound = null;

            NfcManager.setEventListener(NfcEvents.DiscoverTag, (tag) => {
                tagFound = tag;
                resolve(tagFound);
                // NfcManager.setAlertMessageIOS('NDEF tag found');
                // NfcManager.unregisterTagEvent().catch(() => 0);
            });

            NfcManager.setEventListener(NfcEvents.SessionClosed, () => {
                cleanUp();
                if (!tagFound) {
                    resolve();
                }
            });

            NfcManager.registerTagEvent();
        });
    }

    readNFC(){
        const permissions = [
            'android.permission.NFC',
        ];
        //返回得是对象类型
        PermissionsAndroid.requestMultiple(permissions).then(res=>{
            console.log(res);
            NfcManager.isSupported().then(res=>{
                console.log('supported: ',res);
                this.readNdef().then(res=>{
                    console.log('success: ',res);
                    console.log('success: ',res.id);
                    // ToastUtil.info(res)
                    this.setState({
                        flag: false,
                        nfcInfo : JSON.stringify(res)
                    })
                }).catch(e=>{
                    console.log('e: ',e)
                })
            }).catch(e=>{
                console.log(e);
            })
        })



    }


    render() {
        const {flag} = this.state
        return (
            <View style={{flex: 1,alignItems: 'center',justifyContent: 'center'}}>
                <View><Text style={{fontSize: 16,marginBottom: 10}}>请先打开手机NFC功能</Text></View>
                <View>
                    <TouchableOpacity
                        onPress={() => {
                            this.setState({
                                flag: true
                            })
                            this.readNFC()
                        }}
                    >
                        <Text style={{padding: 10,width: 150,backgroundColor: 'blue',fontSize: 16,color: '#fff',textAlign: 'center'}}>
                            {flag?'请放置卡片':'点击开始读取NFC'}
                        </Text>
                    </TouchableOpacity>
                </View>
                <View>
                    <Text>{this.state.nfcInfo}</Text>
                </View>
            </View>

        );
    }
}
export default Msg;
